package com.xywy.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 名称: StringUtils
 * 描述: 字符串处理类
 * 最近修改时间:2014-04-24 11:10
 *
 * @author xgd
 * @since 2014-04-24
 */
public class StringUtils {
    /**
     * 判断字符串是否为Blank
     * “   ”多个空格为blank
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        int strLen = str.length();
        if (str == null || strLen == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }


    /**
     * 判断字符串是否为空
     *
     * @param str 字符串
     * @return 空:true  非空:false
     */
    public static boolean isNull(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * 判断文件是否为空
     *
     * @param file 文件file
     * @return 空:true  非空:false
     */
    public static boolean isNull(File... file) {
        if (null == file) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串数组是否为空
     *
     * @param str 字符串数组
     * @return 空:true  非空:false
     */
    public static boolean isNull(String[] str) {
        if (null == str || str.length == 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断对象是否为空
     *
     * @param obj 对象
     * @return 空:true  非空:false
     */
    public static boolean isObjNull(Object obj) {
        if (null == obj || "".equals(obj) || "null".equals(obj)) {
            return true;
        }
        return false;
    }

    /**
     * 字符串编码
     *
     * @param str    编码字符串
     * @param format 编码类型 如：UTF-8
     * @return 编码后的字符串
     */
    public static String enCode(String str, String format) {
        String result = "";
        try {
            result = URLEncoder.encode(str, format);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 字符串解码
     *
     * @param str    编码字符串
     * @param format 编码类型 如：UTF-8
     * @return 解码后的字符串
     */
    public static String decode(String str, String format) {
        try {
            return URLDecoder.decode(str, format);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将unicode字符串转换成 Utf-8
     *
     * @param theString
     * @return 转码后UTF-8字符串
     */
    public static String unicodeToUtf8(String theString) {
        char aChar;
        if (isNull(theString))
            return "";
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                //throw new IllegalArgumentException(
                                //		"Malformed   \\uxxxx   encoding.");
                                //非unicode字符直接返回""方便判断
                                return "";
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     * 输入流转换string
     *
     * @param in
     * @return
     * @throws java.io.IOException
     */
    public static String inputStreamToString(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    private static Random sRandGen = new Random();
    /**
     * Array of numbers and letters. Numbers appear in the list
     * twice so that there is a more equal chance that a number will be picked.
     * We can use the array to get a random number or letter by picking a random
     * array index.
     */
    private static char[] sNumbersAndLetters =("0123456789abcdefghijklmnopqrstuvwxyz0123456789").toCharArray();
    /**
     * Returns a random String of numbers and letters (lower and upper case) of
     * the specified length. The method uses the Random class that is built-in
     * to Java which is suitable for low to medium grade security uses. This
     * means that the output is only pseudo random, i.e., each number is
     * mathematically generated so is not truly random.
     * <p>
     * The specified length must be at least one. If not, the method will return null.
     *
     * @param length the desired length of the random String to return.
     * @return a random String of numbers and letters of the specified length.
     */
    public static String randomString(int length) {
        if (length < 1) {
            return null;
        }
        // Create a char buffer to put random letters and numbers in.
        final char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = sNumbersAndLetters[sRandGen.nextInt(sNumbersAndLetters.length - 1)];
        }

        return new String(randBuffer);
    }

    /**
     * 验证手机号
     * @param mobiles
     * @return
     */
    public static boolean valMobileNumber(String mobiles) {
        Pattern pattern = Pattern.compile("1[0-9]{10}");
        Matcher m = pattern.matcher(mobiles);
        if (m.matches()) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * 验证邮箱
     * @param strEmail
     * @return
     */
    public static boolean isEmail(String strEmail) {
        String strPattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        if (m.matches()) {
            return true;
        }else {
            return false;
        }
    }
}
